<script>
	// #ifdef APP-PLUS
	var jpushModule = uni.requireNativePlugin("JG-JPush");
	var audioObj = uni.getBackgroundAudioManager();
	// #endif
	import {
		useChatStore,
		useGroupStore,
		useSocketStore,
		useUserStore,
		useStartTodoPolling,
		useVersionStore
	} from '@/pinia-store/user'
	import {
		mapStores
	} from 'pinia'
	import setting from '@/apis/cloud/setting';
	import {
		nextCloudApi
	} from '@/apis/cloud/chat.js';


	export default {
		data() {
			return {
				startTodoPolling: null,
				versionStore: null
			}
		},
		computed: {
			...mapStores(useChatStore, useGroupStore, useUserStore, useSocketStore, useStartTodoPolling, useVersionStore),
		},
		onLaunch: function() {
			uni.$once('saveDevice', () => {
				this.saveSystemInfo();
			})

			this.getNextCloud();

			// #ifdef H5
			// WebPush 初始化
			this.initWebPush();
			let audioInstance = null;
			let shouldReplay = false;
			let audioUnlockModalShown = false; // 新增标志位，只弹一次 Modal
			// 初始化音频实例（只执行一次）
			function initAudioInstance() {
				if (!audioInstance) {
					audioInstance = new Audio();
					audioInstance.src = 'https://cloud.mfarmers.com/cloud-h5/static/sound/lgv.mp3';
				}
			}

			// 安全播放音频（跨浏览器）
			function safePlayAudio() {
				initAudioInstance();

				try {
					if (!audioInstance.paused) {
						audioInstance.pause();
					}
					audioInstance.currentTime = 0;
					audioInstance.play().then(() => {}).catch(err => {
						console.warn('[音频] 播放失败:', err);
					});
				} catch (err) {
					console.error('[音频] 播放异常:', err);
				}
			}

			// 用户首次点击，解锁播放权限（必须）
			document.addEventListener('click', () => {
				safePlayAudio(); // 播一次再暂停，解锁权限

				audioInstance.pause();

				unlockAudioWithModal()
			}, {
				once: true
			});


			// 页面进入后台 / 前台日志
			document.addEventListener('visibilitychange', () => {
				if (document.visibilityState === 'hidden') {
					// console.log('[页面] 进入后台');
					// 设置标志位，可能丢失播放
					shouldReplay = true;
					// this.socketStore.reconnect()
				} else if (document.visibilityState === 'visible') {
					// console.log('[页面] 回到前台');
					if (shouldReplay) {
						// safePlayAudio(); // 补播一次
						shouldReplay = false;
					}
				}
			});

			function unlockAudioWithModal() {
				const hasUnlocked = uni.getStorageSync('audioUnlocked') || '0';

				if (hasUnlocked === '1' || audioUnlockModalShown) {
					return;
				}

				audioUnlockModalShown = true;
				// uni.showModal({
				//   title: '开启音效通知',
				//   content: '请点击确定以开启通知铃声',
				//   cancelText: '取消',
				//   confirmText: '确定',
				//   success: (res) => {
				//     if (res.confirm) {
				initAudioInstance();
				audioInstance.play().then(() => {
					audioInstance.pause();
					audioInstance.currentTime = 0;
					uni.setStorageSync('audioUnlocked', '1');
				}).catch((err) => {
					console.warn('[音频] 解锁失败', err);
				});
				// } else {
				//   audioUnlockModalShown = false
				//   console.log('用户取消了音效解锁');
				//     }
				//   }
				// });
			}

			uni.$on('playNotifyAudio', (value) => {
				if (value == 'login') {
					unlockAudioWithModal()
					uni.setStorageSync('audioUnlocked', '0');
					audioUnlockModalShown = false
				} else {
					safePlayAudio();
				}
			});
			// #endif

			// #ifdef APP-PLUS
			// uni.$on('initJpush', (phone) => {
			// 	this.initJpush(phone);
			// })

			uni.$on('playNotifyAudio', () => {
				try {
					const player = plus.audio.createPlayer(
						'https://cloud.mfarmers.com/cloud-h5/static/sound/lgv.mp3');
					player.play(() => {}, (e) => {});
				} catch (e) {}
			});
			//#endif
			
		},
		onShow() {
			if (!this.startTodoPolling) {
				this.startTodoPolling = useStartTodoPolling()
			}

			if (!this.versionStore) {
				this.versionStore = useVersionStore()
			}
			this.versionStore.checkVersion();
			this.startTodoPolling.start();

			if (this.versionStore.hasUpdate) {
				uni.setTabBarBadge({
					index: 4,
					text: '新'
				})
			} else {
				uni.removeTabBarBadge({
					index: 4
				})
			}
		},
		onHide() {
			this.startTodoPolling.stop();
		},
		methods: {
			//初始化WebPush
			async initWebPush() {
				if ('serviceWorker' in navigator) {
					try {
						//scope不能少，不然service-worker找不到资源
						await navigator.serviceWorker.register('./sw.js', {
							scope: '/'
						});
						console.log('✅ Service Worker 注册成功');
					} catch (err) {
						console.error('❌ Service Worker 注册失败:', err);
					}
				}
			},
			async nextCloudLogin() {
				const msg = await nextCloudApi(this.userStore.user.token);

				if (msg.ocs?.meta?.statuscode == 200) {
					uni.setStorage({
						key: 'next_cloud',
						data: msg.ocs?.data,
						success() {
							console.log('nc存储成功')
						},
						fail(err) {
							console.log('nc存储失败')
						}
					});
				}
			},
			getNextCloud() {
				const _self = this;
				if (this.userStore && this.userStore.user) {
					_self.nextCloudLogin();
				}
			},
			saveSystemInfo() {
				uni.getSystemInfo({
					success: async (res) => {
						const params = {
							worker_name: this.userStore.user.worker_name,
							worker_id: this.userStore.user.worker_id,
							brand: res.brand ? res.brand : '',
							model: res.model ? res.model : '',
							system: res.system ? res.system : '',
							platform: res.platform ? res.platform : ''
						}

						const msg = await setting.saveDeviceData(params);
					}
				});
			},
			// initJpush(phone) {
			// 	jpushModule.initJPushService();
			// 	jpushModule.setLoggerEnable(true);
			// 	plus.screen.lockOrientation("portrait-primary");
			// 	// 设置别名
			// 	jpushModule.setAlias({
			// 		'alias': phone,
			// 		'sequence': 1
			// 	})
			// 	//监听 极光推送连接状态
			// 	this.getNotificationEnabled();
			// 	jpushModule.addConnectEventListener(result => {
			// 		let connectEnable = result.connectEnable
			// 		uni.$emit('connectStatusChange', connectEnable)
			// 	});
			// 	jpushModule.addNotificationListener(result => { //极光推送的消息通知回调
			// 		jpushModule.setBadge(0);
			// 		plus.runtime.setBadgeNumber(0);
			// 		let notificationEventType = result.notificationEventType
			// 		let woopId = result.extras && result.extras.dataType === 'woop' && result.extras.value;
			// 		// 点击事件
			// 		if (notificationEventType == 'notificationOpened') {
			// 			const data = result.extras;
			// 			console.log('点击事件', data)
			// 			if (data.type == 'friend') {
			// 				const friend = {
			// 					friend_account: data.fromAcount,
			// 					friend_phone: data.fromPhone,
			// 					username: data.fromName,
			// 					friend_avatar: data.avatar,
			// 				}
			// 				this.socketStore.nowDialogId = data.dialogId;
			// 				this.chatStore.setChat(friend);
			// 				uni.navigateTo({
			// 					url: '/pages/chat/message/chat/chat'
			// 				})
			// 			}
			// 			if (data.type == 'group') {
			// 				const group = {
			// 					group_id: data.groupId,
			// 					group_name: data.groupName
			// 				}
			// 				this.groupStore.setGroup(group);
			// 				uni.navigateTo({
			// 					url: '/pages/chat/message/group'
			// 				})
			// 			}
			// 		}
			// 	});
			// 	uni.$on('connectStatusChange', (connectStatus) => {
			// 		var connectStr = ''
			// 		if (connectStatus == true) {
			// 			connectStr = '已连接'
			// 			// this.getRegistrationID()
			// 		} else {
			// 			connectStr = '未连接'
			// 		}
			// 		console.log('监听到了连接状态变化 --- ', connectStr)
			// 		this.connectStatus = connectStr
			// 	})
			// 	jpushModule.isPushStopped(res => {
			// 		// code   0已停止推送  1未停止推送
			// 		const {
			// 			code
			// 		} = res
			// 		console.log(res, '安卓连接状态');
			// 	})
			// },
			// getRegistrationID() { //获取registerID
			// 	jpushModule.getRegistrationID(result => {
			// 		let registerID = result.registerID
			// 		console.log(registerID)
			// 		this.registrationID = registerID
			// 		uni.setStorageSync("registerID", registerID)
			// 	})
			// },
			// getNotificationEnabled() {
			// 	if (uni.getSystemInfoSync().platform == "ios") {
			// 		jpushModule.requestNotificationAuthorization((result) => {
			// 			let status = result.status
			// 			if (status < 2) {
			// 				this.noticMsgTool()
			// 			}
			// 		})
			// 	} else {
			// 		jpushModule.isNotificationEnabled((result) => { //判断android是否打开权限
			// 			if (result.code == 0) { //如果为0则表示 未打开通知权限
			// 				this.noticMsgTool()
			// 			}
			// 		})
			// 	}
			// },
			noticMsgTool() {
				if (uni.getSystemInfoSync().platform == "ios") {
					//苹果打开对应的通知栏
					uni.showModal({
						title: '通知权限开启提醒',
						content: '您还没有开启通知权限，无法接受到消息通知，请前往设置！',
						showCancel: false,
						confirmText: '去设置',
						success: function(res) {
							if (res.confirm) {
								var app = plus.ios.invoke('UIApplication', 'sharedApplication');
								var setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:');
								plus.ios.invoke(app, 'openURL:', setting);
								plus.ios.deleteObject(setting);
								plus.ios.deleteObject(app);
							}
						}
					});
				} else {
					//android打开对应的通知栏
					var main = plus.android.runtimeMainActivity();
					var pkName = main.getPackageName();
					var uid = main.getApplicationInfo().plusGetAttribute("uid");
					uni.showModal({
						title: '通知权限开启提醒',
						content: '您还没有开启通知权限，无法接受到消息通知，请前往设置！',
						showCancel: false,
						confirmText: '去设置',
						success: function(res) {
							if (res.confirm) {
								var Intent = plus.android.importClass('android.content.Intent');
								var Build = plus.android.importClass("android.os.Build");
								//android 8.0引导
								if (Build.VERSION.SDK_INT >= 26) {
									var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
									intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
								} else if (Build.VERSION.SDK_INT >= 21) { //android 5.0-7.0
									var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
									intent.putExtra("app_package", pkName);
									intent.putExtra("app_uid", uid);
								} else { //(<21)其他--跳转到该应用管理的详情页
									intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
									var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
									intent.setData(uri);
								}
								// 跳转到该应用的系统通知设置页
								main.startActivity(intent);
							}
						}
					});
				}
			},
		},
	};
</script>
<style>
	@import 'remixicon/fonts/remixicon.css';
</style>
<style lang="scss">
	/*每个页面公共css */
	@import '@/uni_modules/uview-plus/theme.scss';
	@import "@/uni_modules/uview-plus/index.scss";
</style>